//
//  WordViewController.m
//  XiangMuB
//
//  Created by 999999999999 on 16/8/14.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "WordViewController.h"
#import "WordViewCell.h"
#import "WordModel.h"
#import "URL_HeaderDefine.h"
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>
#import "Content.h"
#import "UIView+BSFrame.h"
#import <AFNetworking+RXHeader.h>
@interface WordViewController ()

@property (nonatomic,strong)NSMutableArray *dataArray;
//当前页码
@property (nonatomic,assign)NSInteger page;
//当加载下一页数据时需要这个参数
@property(nonatomic,strong)NSString *maxtime;
//上一次请求的参数
@property (nonatomic,strong)NSDictionary *params;


@end

@implementation WordViewController

-(NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return  _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpTable];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WordViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    //先刷新控件在处理数据
    [self setUpRefresh];
    //注册cell
}
#pragma mark----初始化tableview
-(void)setUpTable{
    //  设置内边距
    CGFloat bottom = self.tabBarController.tabBar.height;
    CGFloat top =TitlesViewY +TitlesViewH;
    self.tableView.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    //设置滚动条内边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    //分割线
    self.tableView.separatorStyle = UITableViewRowAnimationNone;
    self.tableView.backgroundColor = [UIColor clearColor];

}
#pragma mark----刷新数据
-(void)setUpRefresh{
    //下拉刷新,在主线程结束刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)];
//    根据拖拽比例自动改变透明度
    self.tableView.header.autoChangeAlpha = YES;
    //进入页面自动刷新
    [self.tableView.mj_header beginRefreshing];
    //下拉刷新,加载更多数据
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)];
//    self.tableView.footer.hidden = YES;
//    [self loadNewTopics];
}
#pragma mark ---数据处理
//在家新的帖子数据
-(void)loadNewTopics{
    
    [self.tableView.mj_footer endRefreshing];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"data";
    params[@"type"] = @"29";
    self.params = params;

    __weak typeof(self) weakSelf = self;
    [[AFHTTPSessionManager manager]GET:TOPIC_url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        
        //        NSLog(@"=-=-=-=%@",dic);
                if (self.params != params)return;
                // 存储maxtime(maxtime为加载下一页时使用)
                self.maxtime = responseObject[@"info"][@"maxtime"];
        
                for (NSDictionary *dic2  in responseObject[@"list"]) {
                    WordModel *model = [[WordModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic2];
                    [self.dataArray addObject:model];
                }
        
                dispatch_async(dispatch_get_main_queue(), ^{
                      if (self.params != params)return;
                    //结束刷新
                    [weakSelf.tableView.mj_header endRefreshing];
                    [weakSelf.tableView reloadData];
                    
                });

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.params != params)return;
            //结束刷新
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView reloadData];
            
        });
    }];
}
//加载更多的帖子数据
-(void)loadMoreTopics{
//    NSLog(@"======%s",__func__);
    //
    
    [self.tableView.mj_header endRefreshing];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"data";
    params[@"type"] = @"29";
    NSInteger page = self.page + 1;
    //页码
    params[@"page"] = @(page);
    params[@"maxtime"]=self.maxtime;
    self.params = params;
    
    __weak typeof(self) weakSelf = self;
    [[AFHTTPSessionManager manager]GET:TOPIC_url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (self.params != params)return;
        // 存储maxtime(maxtime为加载下一页时使用)
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        for (NSDictionary *dic2  in responseObject[@"list"]) {
            WordModel *model = [[WordModel alloc]init];
            [model setValuesForKeysWithDictionary:dic2];
            [self.dataArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.params != params)return;
            //结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView reloadData];
            weakSelf.page++;
            
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.params != params)return;
            //结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView reloadData];
            
        });
    }];
}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WordViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[WordViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
    }

    WordModel *model = self.dataArray[indexPath.row];
    cell.model = model;

    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    WordModel *model = self.dataArray[indexPath.row];
    NSString *string = model.text;
    
     CGFloat height = [string boundingRectWithSize:CGSizeMake(self.tableView.bounds.size.width - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil].size.height;
    
    
    return 10 + 40 + 10 + height + 10+10 +10;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
